<?php
/*
 * 渠道数据模型
 * 
 */
class Ditches_Model{

	private $tablename = 'ditches';
	private $db;

	function __construct(){
		$this -> db = Database::getInstance();
	}

	/*
	 * 添加数据
	 * @theData (array)
	 */
	function addData($theData){
		$kItem = array();
        $dItem = array();
        foreach ($theData as $key => $data) {
            $kItem[] = $key;
            $dItem[] = $data;
        }
        $field = implode(',', $kItem);
        $values = "'" . implode("','", $dItem) . "'";
        $this->db->query("INSERT INTO " . DB_PREFIX . $this->tablename." ($field) VALUES ($values)");
        $id = $this->db->insert_id();
        return $id;
	}

	/*
	 * 删除数据
	 * @id (int)
	 */
	function delData($id){
		$usersql = '';
		if(ROLE!=ROLE_ADMIN){
			// 如果不是管理员，则加上用户限制
			$usersql = " AND `uid` = ".UID." ";
		}
		$sqlSegment = " DELETE FROM `".DB_PREFIX.$this->tablename."` WHERE `id` = $id $usersql ";
		$this -> db -> query($sqlSegment);
	}

	/*
	 * 更新数据
	 * @theData (array)
	 * @id (int)
	 */
	function updateData($theData,$id){
		$usersql = '';
		if(ROLE!=ROLE_ADMIN){
			// 如果不是管理员，则加上用户限制
			$usersql = " AND `uid` = ".UID." ";
		}
		$Item = array();
        foreach ($theData as $key => $data) {
            $Item[] = "$key='$data'";
        }
        $upStr = implode(',', $Item);
        $this->db->query("update ".DB_PREFIX.$this->tablename." set $upStr where id=$id $usersql ");

	}

	/*
	 * 获取单条数据
	 * @id (int)
	 */
	function getOneData($id){
		$sqlSegment = " SELECT * FROM `".DB_PREFIX.$this->tablename."` WHERE `did` = $id ";
		$row = $this -> db -> once_fetch_array($sqlSegment);
		$row['description'] = htmlspecialchars($row['description']);
		return $row;
	}

 	/*
 	 * 获取多条数据
 	 * @condition (string)
 	 * @pagesize (int)
 	 * @page (int)
 	 */
	function getDatas($condition,$pagesize=30,$page=null){
		if($page!=null){
			$start = ($page-1)*$pagesize;
			$limit = $pagesize;
			$sqlSegment = " SELECT * FROM `".DB_PREFIX.$this->tablename."` WHERE 1=1 $condition LIMIT $start,$limit ";
		}else{
			$sqlSegment = " SELECT * FROM `".DB_PREFIX.$this->tablename."` WHERE 1=1 $condition ";
		}
		
		$res = $this -> db -> query($sqlSegment);
		$returnData = array();
		while($row = $this -> db -> fetch_array($res)){
			$row['description'] = htmlspecialchars($row['description']);
			$returnData[] = $row;
		}
		return $returnData;
	}



}